package com.frxuexi.mynews.activity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.frxuexi.mynews.R
import com.frxuexi.mynews.databinding.ActivityLoginBinding
import com.frxuexi.mynews.entity.NewsTypeEntity
import com.frxuexi.mynews.intent.LoginIntent
import com.frxuexi.mynews.intent.NewsIntent
import com.frxuexi.mynews.state.LoginState
import com.frxuexi.mynews.state.NewsTypeState
import com.frxuexi.mynews.viewmodel.LoginViewModel
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch

@Route(path = "/app/LoginActivity")
class LoginActivity : AppCompatActivity() {
    lateinit var db:ActivityLoginBinding
    lateinit var vm:LoginViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        db=ActivityLoginBinding.inflate(layoutInflater)
        setContentView(db.root)
        vm=ViewModelProvider(this).get(LoginViewModel::class.java)

        db.loginClose.setOnClickListener{
            finish()
        }

        //类型列表数据
        lifecycleScope.launch {
            vm.loginState.collect{
                when(it){
                    is LoginState.onSucess->
                    {
                        Log.i("===",it.data.toString())
                        MMKV.defaultMMKV().encode("token",it.data)
                        finish()
                    }
                    is LoginState.onError->
                        Log.i("===",it.msg)
                    else -> {}
                }
            }
        }

        db.btnLogin.setOnClickListener {
            val name = db.username.text.toString()
            val pass = db.password.text.toString()
            if(name.isEmpty()||pass.isEmpty()){
                Toast.makeText(this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            //1[0-9]{10}
            if(!name.matches(Regex("[A-z][0-9A-z_]{3,9}"))){
                Toast.makeText(this, "用户名为数字或字母或下划线3到9位", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            lifecycleScope.launch {
                vm.channel.send(LoginIntent.login(name,pass))
            }
        }
    }
}